package database

import (
	"bytes"
	"database/sql"
	"fmt"
	"shqsoft.cn/pasnj/base"
	"time"
)

//DataLoader 数据加载接口
type DataLoader interface {
	LoadDataByTable(string, []string, string, string) (*sql.Rows, error)
	LoadDataBySQL(string, ...interface{}) (*sql.Rows, error)
	LoadDataByProc(string, ...interface{}) (*sql.Rows, error)
	GetStartEndTime() (*time.Time, *time.Time, error)
}

//newDataLoader 创建数据加载接口
func newDataLoader() (DataLoader, error) {
	dbType := base.Context.Database.DbType
	switch dbType {
	case "mssql":
		mssql := new(MSSQLDB)
		return mssql, nil
	case "postgres":
		cr := new(CockroachDB)
		return cr, nil
	default:
		return nil, fmt.Errorf("数据库类型%s暂时没有实现！", dbType)
	}
}

func loadDataBySQL(sqlstr string, params ...interface{}) (*sql.Rows, error) {
	rows, err := base.DB.DB().Query(sqlstr, params...)
	if err != nil {
		return nil, err
	}
	return rows, nil
}

func getStartEndTime() (*time.Time, *time.Time, error) {
	sqlstr := "SELECT dfdt,sydt FROM t_conf_sydt"
	rows, err := base.DB.DB().Query(sqlstr)
	defer rows.Close()
	if err != nil {
		return nil, nil, fmt.Errorf("获取系统追溯时间时出错！%s", err)
	}
	if rows.Next() {
		var start, end time.Time
		if err := rows.Scan(&start, &end); err != nil {
			return nil, nil, fmt.Errorf("获取系统追溯时间时出错！%s", err)
		}
		return &start, &end, err
	}
	return nil, nil, fmt.Errorf("获取系统追溯时间时出错！在表conf_sydt中没有找到行！")
}

func loadDataByTable(tableName string, columns []string, orderColName, direction string) (*sql.Rows, error) {
	var buff bytes.Buffer
	clen := len(columns)
	buff.WriteString("SELECT ")
	for i, col := range columns {
		buff.WriteString(col)
		if i < clen-1 {
			buff.WriteString(",")
		}
	}
	buff.WriteString(" FROM ")
	buff.WriteString(tableName)
	if orderColName != "" {
		buff.WriteString(" ORDER BY ")
		buff.WriteString(orderColName)
		buff.WriteString(" ")
		buff.WriteString(direction)
	}
	sqlstr := buff.String()
	return loadDataBySQL(sqlstr)
}

//DefaultDataLoader 默认的数据加载器
var DefaultDataLoader DataLoader

func init() {
	var err error
	DefaultDataLoader, err = newDataLoader()
	if err != nil {
		panic(err)
	}
}
